# LocalStack Resource Provider Scaffolding v2
from __future__ import annotations

from pathlib import Path
from typing import Optional, TypedDict

import localstack.services.cloudformation.provider_utils as util
from localstack.services.cloudformation.resource_provider import (
    OperationStatus,
    ProgressEvent,
    ResourceProvider,
    ResourceRequest,
)


class EC2VPCEndpointProperties(TypedDict):
    ServiceName: Optional[str]
    VpcId: Optional[str]
    CreationTimestamp: Optional[str]
    DnsEntries: Optional[list[str]]
    Id: Optional[str]
    NetworkInterfaceIds: Optional[list[str]]
    PolicyDocument: Optional[str | dict]
    PrivateDnsEnabled: Optional[bool]
    RouteTableIds: Optional[list[str]]
    SecurityGroupIds: Optional[list[str]]
    SubnetIds: Optional[list[str]]
    VpcEndpointType: Optional[str]


REPEATED_INVOCATION = "repeated_invocation"


class EC2VPCEndpointProvider(ResourceProvider[EC2VPCEndpointProperties]):
    TYPE = "AWS::EC2::VPCEndpoint"  # Autogenerated. Don't change
    SCHEMA = util.get_schema_path(Path(__file__))  # Autogenerated. Don't change

    def create(
        self,
        request: ResourceRequest[EC2VPCEndpointProperties],
    ) -> ProgressEvent[EC2VPCEndpointProperties]:
        """
        Create a new resource.

        Primary identifier fields:
          - /properties/Id

        Required properties:
          - VpcId
          - ServiceName

        Create-only properties:
          - /properties/ServiceName
          - /properties/VpcEndpointType
          - /properties/VpcId

        Read-only properties:
          - /properties/NetworkInterfaceIds
          - /properties/CreationTimestamp
          - /properties/DnsEntries
          - /properties/Id

        IAM permissions required:
          - ec2:CreateVpcEndpoint
          - ec2:DescribeVpcEndpoints

        """
        model = request.desired_state
        create_params = util.select_attributes(
            model,
            [
                "PolidyDocument",
                "PrivateDnsEnabled",
                "RouteTablesIds",
                "SecurityGroupIds",
                "ServiceName",
                "SubnetIds",
                "VpcEndpointType",
                "VpcId",
            ],
        )

        if not request.custom_context.get(REPEATED_INVOCATION):
            response = request.aws_client_factory.ec2.create_vpc_endpoint(**create_params)
            model["Id"] = response["VpcEndpoint"]["VpcEndpointId"]
            model["DnsEntries"] = response["VpcEndpoint"]["DnsEntries"]
            model["CreationTimestamp"] = response["VpcEndpoint"]["CreationTimestamp"]
            model["NetworkInterfaceIds"] = response["VpcEndpoint"]["NetworkInterfaceIds"]
            request.custom_context[REPEATED_INVOCATION] = True
            return ProgressEvent(
                status=OperationStatus.IN_PROGRESS,
                resource_model=model,
                custom_context=request.custom_context,
            )

        response = request.aws_client_factory.ec2.describe_vpc_endpoints(
            VpcEndpointIds=[model["Id"]]
        )
        if not response["VpcEndpoints"]:
            return ProgressEvent(
                status=OperationStatus.FAILED,
                resource_model=model,
                custom_context=request.custom_context,
                message="Resource not found after creation",
            )

        state = response["VpcEndpoints"][0][
            "State"
        ].lower()  # API specifies capital but lowercase is returned
        match state:
            case "available":
                return ProgressEvent(status=OperationStatus.SUCCESS, resource_model=model)
            case "pending":
                return ProgressEvent(status=OperationStatus.IN_PROGRESS, resource_model=model)
            case "pendingacceptance":
                return ProgressEvent(status=OperationStatus.IN_PROGRESS, resource_model=model)
            case _:
                return ProgressEvent(
                    status=OperationStatus.FAILED,
                    resource_model=model,
                    message=f"Invalid state '{state}' for resource",
                )

    def read(
        self,
        request: ResourceRequest[EC2VPCEndpointProperties],
    ) -> ProgressEvent[EC2VPCEndpointProperties]:
        """
        Fetch resource information

        IAM permissions required:
          - ec2:DescribeVpcEndpoints
        """
        raise NotImplementedError

    def delete(
        self,
        request: ResourceRequest[EC2VPCEndpointProperties],
    ) -> ProgressEvent[EC2VPCEndpointProperties]:
        """
        Delete a resource

        IAM permissions required:
          - ec2:DeleteVpcEndpoints
          - ec2:DescribeVpcEndpoints
        """
        model = request.previous_state
        response = request.aws_client_factory.ec2.describe_vpc_endpoints(
            VpcEndpointIds=[model["Id"]]
        )

        if not response["VpcEndpoints"]:
            return ProgressEvent(
                status=OperationStatus.FAILED,
                resource_model=model,
                message="Resource not found for deletion",
            )

        state = response["VpcEndpoints"][0]["State"].lower()
        match state:
            case "deleted":
                return ProgressEvent(status=OperationStatus.SUCCESS, resource_model=model)
            case "deleting":
                return ProgressEvent(status=OperationStatus.IN_PROGRESS, resource_model=model)
            case _:
                request.aws_client_factory.ec2.delete_vpc_endpoints(VpcEndpointIds=[model["Id"]])
                return ProgressEvent(status=OperationStatus.IN_PROGRESS, resource_model=model)

    def update(
        self,
        request: ResourceRequest[EC2VPCEndpointProperties],
    ) -> ProgressEvent[EC2VPCEndpointProperties]:
        """
        Update a resource

        IAM permissions required:
          - ec2:ModifyVpcEndpoint
          - ec2:DescribeVpcEndpoints
        """
        raise NotImplementedError
